﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SceneController : MonoBehaviour
{
    //引用场景中的卡片
    [SerializeField] private MemoryCard originalCard;
    //引用精灵资源的数组
    [SerializeField] private Sprite[] images;

    //产生多少网格以及之间的距离
    public const int gridRows = 2;
    public const int gridCols = 4;
    public const float offsetX = 2;
    public const float offsetY = 2.5f;

    private MemoryCard _firstRevealed;
    private MemoryCard _secondRevealed;

    private int _socre = 0;//得分
    [SerializeField] private TextMesh scoreLabel;

    public bool canReveal
    {
        //当一家存在第二张翻开的卡片时，getter方法返回false
        get { return _secondRevealed == null; }
    }

	// Use this for initialization
	void Start ()
	{
	    int id = Random.Range(0, images.Length);
        //调用MemoryCard中的公有方法
	    originalCard.SetCard(id, images[id]);

        //第一张卡片的位置：所有其他的卡片将从这里开始偏移
	    Vector3 startPos = originalCard.transform.position;

	    int[] numbers = {0, 0, 1, 1, 2, 2, 3, 3};
	    numbers = ShuffleArray(numbers);

	    for (int i = 0; i < gridCols; i++)
	    {
            //嵌套循环定义网格的列和行
	        for (int j = 0; j < gridRows; j++)
	        {
                //用于引用原始卡片或卡片副本的容器
	            MemoryCard card;
	            if (i == 0 && j == 0)
	            {
	                card = originalCard;
	            }
	            else
	            {
	                card = Instantiate(originalCard) as MemoryCard;
	            }

                //从打乱的列表钟取出ID而不是随机生成
	            int index = j * gridCols + i;
	            id = numbers[index];
                card.SetCard(id,images[id]);

	            float posX = (offsetX * i) + startPos.x;
	            float posY = -(offsetY * j) + startPos.y;
	            card.transform.position = new Vector3(posX, posY, startPos.z);
	        }
	    }
	}
	
	// Update is called once per frame
	void Update () {
		
	}

    //Knuth重排算法,洗牌算法
    private int[] ShuffleArray(int[] numbers)
    {
        int[] newArray = numbers.Clone() as int[];
        for (int i = 0; i < newArray.Length; i++)
        {
            int tmp = newArray[i];
            int r = Random.Range(i, newArray.Length);
            newArray[i] = newArray[r];
            newArray[r] = tmp;
        }
        return newArray;
    }

    public void CardRevealed(MemoryCard card)
    {
        //将卡片对象存储在两个卡片变量中的一个，这将取决第一个变量是否已被占用
        if (_firstRevealed == null)
        {
            _firstRevealed = card;
        }
        else
        {
            _secondRevealed = card;
            //比较两个翻开的卡片ID
            //Debug.Log("Match?"+(_firstRevealed.id == _secondRevealed.id));
            //当两张卡片都显示时调用协程
            StartCoroutine(CheckMatch());
        }
    }

    private IEnumerator CheckMatch()
    {
        //如果翻转的卡片ID匹配，则增加分数
        if (_firstRevealed.id == _secondRevealed.id)
        {
            _socre++;
            //text显示设置在文本对象上的属性
            scoreLabel.text = "Score:" + _socre;
        }
        else
        {
            yield return new WaitForSeconds(.5f);
            //如果不匹配则不翻开
            _firstRevealed.Unreveal();
            _secondRevealed.Unreveal();
        }
        //不管是否匹配都清楚变量
        _firstRevealed = null;
        _secondRevealed = null;
    }

    public void Restart()
    {
        Application.LoadLevel("Scene");
    }
}
